#include "linux_link.h"
#include "stdio.h"
#include "../../lv_drv_conf.h"


#if (LV_USE_FS_POSIX == 1)
#include "lv_app.h"
#include <pthread.h>
#include <unistd.h>

#include "uart_com.h"

// static pthread_mutex_t lvgl_mutex;
// static pthread_t lvgl_thread;

union t113_and_stm32_data_t{
	uint8_t tx_buff[50];
	
	struct {
		uint8_t  	rocker[10];
        uint8_t  	user_ch[10];
		uint16_t 	rocker_adc[4];
		uint8_t 	vbat;
		uint8_t 	mode;
	};	
}t113_and_stm32_data;

// uint8_t i=0; 
/* 接收部分 */
void linux_rx(uint8_t fun, uint8_t *data, uint16_t len)
{
    // pthread_mutex_lock(&lvgl_mutex);
    switch(fun)
	{
		case LINUX_LINK_TX_BUFF: {
            for (int i = 0; i < 30; i++)
            {
                t113_and_stm32_data.tx_buff[i] = data[i];
            }
            
			app_ch_calib_set_adc(t113_and_stm32_data.rocker_adc);
            set_show_mode(t113_and_stm32_data.mode);
            set_remote_info(t113_and_stm32_data.rocker);
            set_remote_info_for_ch_set(t113_and_stm32_data.rocker);
            // i++;
            // printf("Fuyb %d\n", i);
			break;
		}
    }
    // pthread_mutex_unlock(&lvgl_mutex);
}

static void linux_32_tx_calib(uint16_t *data)
{
    Comm_tx(LINUX_LINK_CALIB, (uint8_t *)data, 8*2);
}

static void linux_32_buzz_di(void)
{
    Comm_tx_uint8(LINUX_LINK_BUZZ, 1);
}

static void linux_32_tx_mode(uint8_t mode)
{
    Comm_tx_uint8(LINUX_LINK_SETMODE, mode);
}

static void linux_32_tx_u8_2(uint8_t fun, uint8_t data, uint8_t data2)
{
    Comm_tx_uint16(fun, data<<8 | data2);
}

hal_link_t linux_link = {
	.hal_link_handler = NULL,
    .tx_calib_buff = linux_32_tx_calib,
	.tx_mode = linux_32_tx_mode,
    .buzz_di = linux_32_buzz_di,
    .tx_u8 = Comm_tx_uint8,
    .tx_u8_2 = linux_32_tx_u8_2,
};

// static void *lvgl_thread_fun(void *arg)
// {
//     while(1) {
//         pthread_mutex_lock(&lvgl_mutex);
//         lv_task_handler();
//         pthread_mutex_unlock(&lvgl_mutex);
//         usleep(30 * 1000); /* sleep for 10 ms */
//     }

//     return NULL;
// }

void linux_link_init(void)
{
    char buffer;

    set_channel_user_ch_p(t113_and_stm32_data.user_ch);
    
    Action_init();

    Comm_tx_uint8(LINUX_LINK_BUZZ, 1);
    while (1)
    {
        lv_task_handler();
        /* code */
        ssize_t bytes_read = read(AcRx.fd, &buffer, 1);
        if (bytes_read > 0) {
			for (int i = 0; i < bytes_read; i++) {
				ActionRx_ForUart(&AcRx, buffer);
			}
        }
    }
    
    // if (pthread_create(&lvgl_thread, NULL, lvgl_thread_fun, NULL) != 0) {
    //     perror("Failed to create data update thread");
    //     return ;
    // }

    // Action_init();

    // // 等待线程结束（这里不会结束，因为是无限循环）
    // pthread_join(lvgl_thread, NULL);

    // pthread_mutex_destroy(&lvgl_mutex);
    close(AcRx.fd);
}

#endif